package com.stedu.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.stedu.bean.Account;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.AdminService;
import com.stedu.utils.JwtUtil;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class AccountController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public RespBean login(String username, String password, String captchaId, String captcha) throws SteduException {

        //判断验证码 - 和 Redis中保存的验证码文本对比
        String captchaRedis = (String) redisUtil.get(captchaId);
        if (captchaRedis == null || (captchaRedis != null && !captchaRedis.equalsIgnoreCase(captcha))){
            return RespBean.error("验证码错误,请刷新后重新输入");
        }

        if (!username.matches("^[a-zA-Z0-9]{1,9}$")) {
            throw new SteduException("用户名只能包含字母或数字，且长度不能超过9位，或用户名不对");
        }

        if (!password.matches("^[0-9]{1,9}$")){
            return RespBean.error("密码只能是数字，且长度不能超过9位");
        }


        //判断用户名和密码是否正确
        Account admin = adminService.login(username, password);

        if (admin == null) {
            return RespBean.error("用户名或密码错误");
        }
        //登录成功后生成JWT发送给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        map.put("permissions", admin.getPermissions());
        map.put("aid", admin.getAid());
        String jwt = JwtUtil.generateJwt(map);
        return RespBean.ok("登录成功", jwt);
    }

    @GetMapping("/ps")
    public RespBean abc(@RequestHeader("token") String token){
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        return RespBean.ok("", map);
    }

    //注销

    @GetMapping("/logout")
    public RespBean logout(HttpSession session){
        //让session失效
        session.invalidate();

        //返回注销成功的消息
        return RespBean.ok("退出成功");
    }

    //验证码
    @GetMapping("/captcha")
    public RespBean captcha(){
        //生成验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 20);
        //获取验证码的文本
        String code = captcha.getCode();
        //生成唯一的ID
        String captchaId = IdUtil.getSnowflakeNextIdStr();
        //获取验证码文本保存在Redis中
        redisUtil.set(captchaId, code, 60);

        // Base64 图片 -- 字符串
        String captchaImageBase64Data = captcha.getImageBase64Data();

        //将captchaId和验证码图片发送给浏览器
        HashMap<String, Object> map = new HashMap<>();
        map.put("captchaId", captchaId);
        map.put("captchaImageBase64Data", captchaImageBase64Data);

        return RespBean.ok("", map);
    }
}
